//
//  MyInfoTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/7.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MyInfoTableViewController.h"
#import "MyInfoBasicMode.h"
#import "UserIconTableViewCell.h"
#import "ZilaioTableViewCell.h"
#import "JianjieViewController.h"
#import "UpdateInfoViewController.h"
#import "ZhanshiPhotoViewController.h"
#import "LCActionSheet.h"
#import "MyCompanyViewController.h"
#import "UserModel.h"
#import <UIImageView+WebCache.h>
#import "IWUploadParam.h"
#import "LikxViewController.h"
#import "Puser.h"
#import "UserInfoUpdateResde.h"
#import "AppDelegate.h"
#import "UpdatePhoneViewController.h"
#import "SubUserManagerController.h"
#import "MyShopInfoTableViewController.h"
@interface MyInfoTableViewController ()<LCActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) NSArray *array;
@property (nonatomic,strong) MyInfoBasicMode *jianjie;
@property (nonatomic,strong) UIImagePickerController *picker;
@end

@implementation MyInfoTableViewController
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationItem.title=@"我的资料";
    self.view.backgroundColor=bgGarycolor;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
  
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}
-(void)setUser:(Puser *)user{
    _user=user;
    [self setupdata];
}

-(void)setupdata{
   NSInteger power=[_user.power integerValue];
    if (power<5) {
        [self setuppersonData];
    }else if(power<9) {
        [self setupcomdata];
    }
    
    
}

-(void)setupcomcumdata{
    MyInfoBasicMode *comusername=[[MyInfoBasicMode alloc]init];
    comusername.name=@"账号名";
    comusername.detail=_user.com_username;
    comusername.HideAccestory=YES;
    
    MyInfoBasicMode *companyname=[[MyInfoBasicMode alloc]init];
    companyname.name=@"所属公司";
    companyname.detail=_user.com_name;
    companyname.HideAccestory=YES;
    
    MyInfoBasicMode *job=[[MyInfoBasicMode alloc]init];
    job.name=@"所属职位";
    job.detail=_user.com_job;
    job.HideAccestory=YES;
    
    MyInfoBasicMode *lianxi=[[MyInfoBasicMode alloc]init];
    lianxi.name=@"联系方式";
    
    lianxi.detail=_user.likn;
    lianxi.block=^{
        LikxViewController *link=[LikxViewController Link];
        link.usermode=_user;
        link.block=^(BOOL ischange){
            if (ischange) {
                lianxi.detail=@"已填写";
            }
        };
        [self.navigationController pushViewController:link animated:YES];
    };
    MyInfoBasicMode *address=[[MyInfoBasicMode alloc]init];
    address.name=@"详细地址";
    
    address.detail=[_user.com_adress isEqualToString:@""]?@"未填写":_user.com_adress;
    address.HideAccestory=YES;
    MyInfoBasicMode *dianpu=[[MyInfoBasicMode alloc]init];
    dianpu.name=@"我的店铺信息";
    dianpu.detail=_user.shopinfo;
    dianpu.block=^{
        MyShopInfoTableViewController *vc=[MyShopInfoTableViewController viewcontroller];
        [self.navigationController pushViewController:vc animated:YES];
    };
     self.array=@[@[comusername,companyname],@[job,lianxi,address,dianpu]];
}

-(void)setupcomdata{
    
    
    if ([_user.power integerValue]==8) {
        [self setupcomcumdata];
    }else{
    MyInfoBasicMode *comusername=[[MyInfoBasicMode alloc]init];
    comusername.name=@"账号名";
    comusername.detail=_user.com_username;
    comusername.HideAccestory=YES;
    
    
    MyInfoBasicMode *renzhen=[[MyInfoBasicMode alloc]init];
    renzhen.name=@"修改认证信息";
    renzhen.detail=@"已填写";
    renzhen.block=^{
       UpdateInfoViewController *upifvc=[[UpdateInfoViewController alloc]init];
        [self.navigationController pushViewController: upifvc animated:YES];
    };
    MyInfoBasicMode *lianxi=[[MyInfoBasicMode alloc]init];
    lianxi.name=@"联系方式";
    
    lianxi.detail=_user.likn;
    lianxi.block=^{
        LikxViewController *link=[LikxViewController Link];
        link.usermode=_user;
        link.block=^(BOOL ischange){
            if (ischange) {
                lianxi.detail=@"已填写";
            }
        };
        [self.navigationController pushViewController:link animated:YES];
    };
    
    
    MyInfoBasicMode *dianpu=[[MyInfoBasicMode alloc]init];
    dianpu.name=@"我的店铺信息";
    dianpu.detail=_user.shopinfo;
    dianpu.block=^{
        MyShopInfoTableViewController *vc=[MyShopInfoTableViewController viewcontroller];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    
    if ([_user.power integerValue]==5) {
        MyInfoBasicMode *subuser=[[MyInfoBasicMode alloc]init];
        subuser.name=@"子账号管理";
        subuser.block=^{
            SubUserManagerController *mvc=[SubUserManagerController viewcontroller];
            [self.navigationController pushViewController:mvc animated:YES];
        };
        self.array=@[@[comusername],@[renzhen,lianxi,subuser,dianpu]];
    }else{
    self.array=@[@[comusername],@[renzhen,lianxi,dianpu]];
    }
   }
}
-(void)setuppersonData{
    MyInfoBasicMode *name=[[MyInfoBasicMode alloc]init];
    name.name=@"姓名";
    name.detail=_user.user_truename;
    name.HideAccestory=YES;
    MyInfoBasicMode *usericon=[[MyInfoBasicMode alloc]init];
    usericon.name=@"个人头像";
    usericon.usericon=_user.user_ico;
    usericon.isIcon=YES;
    usericon.block=^{
        [self alertSelect];
    };
    MyInfoBasicMode *photo=[[MyInfoBasicMode alloc]init];
    photo.name=@"展示照片";
    
    photo.detail=_user.show_pic;
    
    photo.block=^{
        ZhanshiPhotoViewController *zsvc=[ZhanshiPhotoViewController viewcontroller];
        if (self.user.show_pics) {
         NSArray *array= [NSString JsontoData:self.user.show_pics];
            zsvc.photoaray=[NSMutableArray arrayWithArray:array];
        }
        zsvc.navigationItem.title=@"展示照片";
       
        
        [self.navigationController pushViewController:zsvc animated:YES];
    };
    MyInfoBasicMode *jianjie=[[MyInfoBasicMode alloc]init];
    jianjie.name=@"一句话简介";
    if ([_user.user_intro isEqualToString:@""]) {
        jianjie.detail=@"未填写";
        
    }else{
        jianjie.detail=_user.user_intro;
    }
    jianjie.block=^{
        
        JianjieViewController *jjvc=[XHMianStory instantiateViewControllerWithIdentifier:@"jianjie"];
        jjvc.navtitle=@"一句话简介";
        jjvc.mode=_user;
        if (![_user.user_intro isEqualToString:@""]) {
            jjvc.text=jianjie.detail;
        }
        jjvc.block=^(NSString *str){
            jianjie.detail=str;
            [self.tableView reloadData];
            
        };
        [self.navigationController pushViewController: jjvc animated:YES];
    };
    self.jianjie=jianjie;
    MyInfoBasicMode *renzhen=[[MyInfoBasicMode alloc]init];
    renzhen.name=@"修改认证信息";
    if ([_user.power intValue]==4) {
        renzhen.detail=@"未填写";
    }else{
        renzhen.detail=@"已填写";
    }
    renzhen.block=^{
        if ([_user.power intValue]==4) {
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            
            hud.labelText=@"请去开店认证申请";
            hud.mode = MBProgressHUDModeText;
            
            hud.margin = 10.f;
            
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
            return;
        }
        UpdateInfoViewController *upifvc=[[UpdateInfoViewController alloc]init];
        [self.navigationController pushViewController: upifvc animated:YES];
    };
    MyInfoBasicMode *company=[[MyInfoBasicMode alloc]init];
    company.name=@"所属公司";
    if ([_user.user_skype isEqualToString:@""]) {
        company.detail=@"未填写";
    }else{
        company.detail=_user.user_skype;
    }
    
    company.block=^{
        MyCompanyViewController *mycvc=[MyCompanyViewController viewcontroller];
        mycvc.navigationItem.title=@"所属公司";
        [self.navigationController pushViewController:mycvc animated:YES];
    };
    MyInfoBasicMode *phone=[[MyInfoBasicMode alloc]init];
    phone.name=@"注册手机";
    ;
    
    NSString *phonestr=[_user.user_mobile stringByReplacingCharactersInRange: NSMakeRange(3,_user.user_mobile.length-7) withString:@"****"];
    phone.detail=phonestr;
    phone.isPhone=YES;
    phone.block=^{
        UpdatePhoneViewController *vc=[UpdatePhoneViewController Viewcontroller];
        [self.navigationController pushViewController:vc animated:YES];
    };
    MyInfoBasicMode *lianxi=[[MyInfoBasicMode alloc]init];
    lianxi.name=@"联系方式";
    
    lianxi.detail=_user.link;
    lianxi.block=^{
        LikxViewController *link=[LikxViewController Link];
        link.usermode=_user;
        link.block=^(BOOL ischange){
            if (ischange) {
                lianxi.detail=@"已填写";
            }
        };
        [self.navigationController pushViewController:link animated:YES];
    };
    self.array=@[@[name,usericon,photo,jianjie],@[renzhen,company,phone],@[lianxi]];
}

-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor orangeColor];
        
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
         UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self updateUserIcon:image];
        
    }];
    
  
}

-(void)updateUserIcon:(UIImage *)image{
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    hud.labelText=@"正在上传..";
    hud.mode = MBProgressHUDModeIndeterminate;
    
    hud.margin = 10.f;
    
    hud.removeFromSuperViewOnHide = YES;
    IWUploadParam *new_ico=[[IWUploadParam alloc]init];
    new_ico.data= [UIImage compressData:image toMaxFileSize:DefailutPicSize];
    new_ico.mineType=@"jpeg";
  
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    if ([_user.power intValue]<5) {
        params[@"user_type"]=@"person";
        params[@"user_id"]=_user.user_id;
        params[@"action"]=@"p_hand_img";
        new_ico.paramName=@"new_ico";
        new_ico.fileName=@"new_ico.jpeg";
    }else{
        params[@"user_type"]=@"company";
        params[@"com_id"]=_user.com_id;
        params[@"action"]=@"c_logo_change";
        new_ico.paramName=@"new_logo";
        new_ico.fileName=@"new_logo.jpg";
    }
    
    
    
    [PostUitls upload:userinfourl parameters:params uploadarray:@[new_ico] success:^(id responseobj) {
        NSDictionary *dict=responseobj;
        UserInfoUpdateResde *resmode=[UserInfoUpdateResde  resdeWithDict:dict];
        if ([resmode.state intValue]==400) {
            if ([self.user.power integerValue]<5) {
                 self.user.user_ico=resmode.data;
            }else{
                self.user.shop_logo=resmode.data;
            }
           
            
            AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
            [delegate saveContext];
            NSArray *array=self.array[0];
            MyInfoBasicMode *usermode=array[1];
            usermode.usericon=self.user.user_ico;
            [self.tableView reloadData];
            hud.mode=MBProgressHUDModeText;
            hud.labelText=@"上传成功";
            
        }else{
            hud.labelText=@"上传失败";
        }
       [hud hide:YES afterDelay:0.5];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        hud.mode=MBProgressHUDModeText;
        hud.labelText=@"网络错误";
        [hud hide:YES afterDelay:0.5];
    }];
    

    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
   
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)showImagePicker:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}

-(void)alertSelect{
   LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] redButtonIndex:-1 delegate:self];
    [sheet show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==actionSheet.btnCount-1) {
        return;
    }
    if (buttonIndex==0) {
        [self showCarmera:0];
    }else{
        [self showImagePicker:0];
    }
    NSLog(@"index%d",buttonIndex);
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return self.array.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSArray *array=self.array[section];
    return array.count;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.array[indexPath.section];
    
    MyInfoBasicMode *mode=array[indexPath.row];
    if (mode.block) {
        mode.block();
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *array=self.array[indexPath.section];
    
    MyInfoBasicMode *mode=array[indexPath.row];
    if (mode.isIcon) {
        UserIconTableViewCell *cell=[UserIconTableViewCell cell];
        NSString *iconurl=[NSString getImageURLstr: mode.usericon];
        [cell.usericon sd_setImageWithURL:[NSURL URLWithString:iconurl] placeholderImage:[UIImage imageNamed:@"usericon_placehoder"]];
        return cell;
    }else {
        ZilaioTableViewCell *cell=[ZilaioTableViewCell cellWithTablView:tableView];
        if (mode.HideAccestory) {
            cell.accessoryType=UITableViewCellAccessoryNone;
        }else{
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text=mode.name;
        cell.detailTextLabel.text=mode.detail;
        if (mode.isPhone) {
            cell.detailTextLabel.textColor=UIColorWithRGB(4, 139, 239);
        }
        return cell;
    }
    
   
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
